// 将MySQL连接改为SQLite连接
// 将Op操作符的导入移到文件顶部
const { sequelize, Message, User, Op } = require('../Config/sqliteDB.js');
const socketUtil = require('../utils/socketUtil');

// 获取会话消息列表（已有的功能）
exports.getMessagesByConversation = async (req, res) => {
  try {
    const conversationId = req.params.conversationId;

    // 使用Sequelize ORM查询，替代直接SQL
    const messages = await Message.findAll({
      where: { conversation_id: conversationId },
      include: [{
        model: User,
        as: 'sender',
        attributes: ['username']
      }],
      order: [['created_at', 'ASC']]
    });

    res.status(200).json({
      message: '成功获取消息记录',
      data: messages
    });

  } catch (error) {
    console.error('获取消息失败:', error);
    res.status(500).json({ message: '服务器内部错误' });
  }
};

// 发送消息的新功能
exports.sendMessage = async (req, res) => {
  try {
    const { receiverId, content, messageType = 'text' } = req.body;
    const senderId = req.user.id; // 从token中获取发送者ID
    
    // 确定会话ID
    const conversationId = senderId < receiverId ? `${senderId}_${receiverId}` : `${receiverId}_${senderId}`;
    
    // 使用Sequelize的create方法插入数据
    const newMessage = await Message.create({
      sender_id: senderId,
      receiver_id: receiverId,
      conversation_id: conversationId,
      content: content,
      message_type: messageType
    });
    
    // 获取完整的消息信息，包含发送者名称
    const fullMessage = await Message.findByPk(newMessage.id, {
      include: [{
        model: User,
        as: 'sender',
        attributes: ['username']
      }]
    });
    
    // 使用Socket.IO实时发送消息给接收者
    const io = socketUtil.getIO();
    socketUtil.sendToUser(receiverId, 'new-message', fullMessage);
    
    // 返回成功响应
    res.status(201).json({
      message: '消息发送成功',
      data: fullMessage
    });
    
  } catch (error) {
    console.error('发送消息失败:', error.message);
    console.error('错误堆栈:', error.stack);
    res.status(500).json({ message: '服务器内部错误' });
  }
};

// 在文件末尾添加createConversation方法
exports.createConversation = async (req, res) => {
  try {
    const { receiverId } = req.body;
    const senderId = req.user.id;
    
    // 确定会话ID
    const conversationId = senderId < receiverId ? `${senderId}_${receiverId}` : `${receiverId}_${senderId}`;
    
    // 简单实现：直接返回会话信息，不检查是否存在
    // 检查用户是否存在
    const [senderUser, receiverUser] = await Promise.all([
      User.findByPk(senderId),
      User.findByPk(receiverId)
    ]);
    
    if (!senderUser || !receiverUser) {
      return res.status(404).json({ message: '用户不存在' });
    }
    
    res.status(200).json({
      message: '会话获取成功',
      data: {
        conversation_id: conversationId,
        participants: [
          { id: senderId, username: senderUser.username },
          { id: receiverId, username: receiverUser.username }
        ]
      }
    });
    
  } catch (error) {
    console.error('创建会话失败:', error.message);
    res.status(500).json({ message: '服务器内部错误' });
  }
};